package com.example.drzhang.oengldemo.concurrent;

import java.util.concurrent.Executors;
import java.util.concurrent.Semaphore;
import java.util.concurrent.ThreadPoolExecutor;

/**
 * Created by Drzhang on 2017/10/16.
 */

public class SemaphoreTest {

    public static void main (String[] args){
        ThreadPoolExecutor threadPoolExecutor = (ThreadPoolExecutor) Executors.newCachedThreadPool();
        Semaphore semaphore = new Semaphore(3);  //3 个资源可以使用
        for (int i = 0; i < 20; i++) {
            SemaphoreThread thread = new SemaphoreThread("name"+i,semaphore);
            threadPoolExecutor.submit(thread);
        }
        threadPoolExecutor.shutdown();
    }

    private  static class SemaphoreThread extends Thread{
        private String name;
        private Semaphore mSemaphore;

        public SemaphoreThread(String name, Semaphore semaphore) {
            this.name = name;
            mSemaphore = semaphore;
        }

        @Override
        public void run() {
            boolean flag = true;
            while(flag){
                if (mSemaphore.availablePermits() > 0){
                    System.out.println("资源空闲，可以使用");
                }else{
                    System.out.println("资源不足，请稍等");
                    continue;
                }
                try {
                    mSemaphore.acquire();
                    Thread.sleep((long) (Math.random()*1000));
                    mSemaphore.release();
                    flag = false;
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }

        }
    }
}
